/*
 * Copyright (C) 2007-2008  Hylke van der Schaaf
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, in version 3 of the License.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package hextd.message;

import hextd.message.MessageFactory.NetworkMessage;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MessagePlayerInChannel implements Message {

	public NetworkMessage type = NetworkMessage.PlayerInChannel;
	public static String RegExp = "InChannel ([0-9]+) ([0-9]+) (s|r) ([0-9]+)";
	// int channelId, int channelPlayerId Running/Selecting
	public static Pattern MessagePattern = Pattern.compile(MessagePlayerInChannel.RegExp);
	//
	private String message;
	private int channelId;
	private int playerId;
	private boolean running;
	private int lastTick;
	private int senderId = -1;

	public static String formatMessage(Integer channelId, Integer playerId, boolean running, int lastTick) {
		String message = "InChannel " + channelId.toString() + " " + playerId.toString();
		if (running) {
			message += " r";
		} else {
			message += " s";
		}
		message += " " + lastTick;
		return message;
	}

	public MessagePlayerInChannel() {
	}

	private MessagePlayerInChannel(String message) {
		this.message = message;
		Matcher matcher = MessagePlayerInChannel.MessagePattern.matcher(message);
		if (matcher.matches()) {
			try {
				channelId = Integer.parseInt(matcher.group(1));
				playerId = Integer.parseInt(matcher.group(2));
				if (matcher.group(3).equalsIgnoreCase("r")) {
					running = true;
				}
				lastTick = Integer.parseInt(matcher.group(4));
			} catch (NumberFormatException e) {
				System.err.println("MessageInChannel: invalid id in: " + matcher.group(1) + " or " + matcher.group(2));
			}
		}
	}

	public int getChannelId() {
		return this.channelId;
	}

	public int getPlayerId() {
		return this.playerId;
	}

	public int getLastTick() {
		return lastTick;
	}

	public boolean isRunning() {
		return running;
	}

	@Override
	public String getMessage() {
		return this.message;
	}

	@Override
	public Message initFromString(String message) {
		return new MessagePlayerInChannel(message);
	}

	@Override
	public int getSenderId() {
		return this.senderId;
	}

	@Override
	public void setSenderId(int id) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public Pattern getPattern() {
		return MessagePlayerInChannel.MessagePattern;
	}

	@Override
	public NetworkMessage getType() {
		return this.type;
	}
}
